const express = require('express')
const cors = require('cors')
const fs = require('fs')
const path = require('path')

const app = express()
const PORT = process.env.PORT || 3005

// 启用CORS
app.use(cors())

// 解析JSON请求体
app.use(express.json())

// 从poems.json文件中读取诗词数据
const poemsData = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'poems.json'), 'utf8')
)

// 从poem_details.json文件中读取诗词详情数据
let poemDetailsData = { poems: [] }
try {
  poemDetailsData = JSON.parse(
    fs.readFileSync(path.join(__dirname, 'poem_details.json'), 'utf8')
  )
} catch (error) {
  console.error('读取poem_details.json文件失败:', error)
}

// 获取单个诗歌详情接口
app.get('/api/poems/:id', (req, res) => {
  const id = req.params.id
  const numId = parseInt(id)

  // 先从详情数据中查找 - 尝试多种ID格式匹配
  let poemDetail = poemDetailsData.poems.find((p) => 
    p.id === id || // 字符串ID完全匹配
    p.id === numId || // 数字ID匹配
    parseInt(p.id) === numId // 将字符串ID转为数字后匹配
  )

  // 如果在详情数据中没找到，则从poems.json中查找
  if (!poemDetail) {
    // 从所有类型的诗词中查找
    const allNewPoems = Object.values(poemsData).flat()
    const poem = allNewPoems.find((p) => p.id === numId)

    if (poem) {
      // 尝试再次在详情数据中查找匹配的诗词
      // 通过标题和作者进行匹配
      const matchByTitleAuthor = poemDetailsData.poems.find(
        (p) => p.title === poem.title && p.author === poem.author
      )

      if (matchByTitleAuthor) {
        // 如果找到匹配的详情，使用详情数据
        poemDetail = matchByTitleAuthor
      } else {
        // 将找到的诗转换为详情格式
        poemDetail = {
          id: poem.id.toString(),
          title: poem.title,
          author: poem.author,
          dynasty: poem.dynasty,
          content: poem.content.replace(/，/g, '，\n'),
          translation: '暂无翻译',
          appreciation: '暂无赏析',
        }
      }
    }
  }

  if (!poemDetail) {
    return res.status(404).json({
      code: 404,
      message: 'poem not found',
    })
  }

  res.json({
    code: 200,
    message: 'success',
    data: poemDetail,
  })
})

// 新增获取指定类型诗词列表的接口（使用params参数）
app.get('/api/poems/type/:type/:page?/:limit?', (req, res) => {
  const { type, page = 1, limit = 10 } = req.params

  // 验证type参数是否有效
  if (!['daily', 'tang', 'song', 'yuan'].includes(type)) {
    return res.status(400).json({
      code: 400,
      message:
        'Invalid type parameter. Valid values are: daily, tang, song, yuan',
    })
  }

  // 获取指定类型的诗词
  const typePoems = poemsData[type] || []

  let paginatedPoems = []

  // 解析分页参数
  const pageNum = parseInt(page)
  const limitNum = parseInt(limit)

  // 对daily类型进行特殊处理，每次随机返回不同的诗歌
  if (type === 'daily') {
    // 随机打乱daily类型的诗词数组
    const shuffledPoems = [...typePoems].sort(() => Math.random() - 0.5)
    // 从打乱后的数组中取出指定数量的诗词
    paginatedPoems = shuffledPoems.slice(0, limitNum)
  } else {
    // 其他类型的诗词仍然使用分页
    const startIndex = (pageNum - 1) * limitNum
    const endIndex = pageNum * limitNum
    paginatedPoems = typePoems.slice(startIndex, endIndex)
  }

  // 构建响应数据
  const response = {
    code: 200,
    message: 'success',
    data: paginatedPoems,
    collect_count: typePoems.length,
    total: typePoems.length,
    page: pageNum,
    limit: limitNum,
    type,
  }

  res.json(response)
})

// 从discover.json文件中读取发现页数据
let discoverData = {}
try {
  discoverData = JSON.parse(
    fs.readFileSync(path.join(__dirname, 'discover.json'), 'utf8')
  )
} catch (error) {
  console.error('读取discover.json文件失败:', error)
}

// 发现页接口 - 根据kind参数返回不同类型的数据
app.get('/api/discover', (req, res) => {
  const { kind = 'authors', limit = 6 } = req.query
  console.log(kind)

  // 验证kind参数是否有效
  if (!['authors', 'themes', 'dynasties', 'forms'].includes(kind)) {
    return res.status(400).json({
      code: 400,
      message:
        'Invalid kind parameter. Valid values are: authors, themes, dynasties, forms',
    })
  }

  // 获取指定类型的数据
  const kindData = discoverData[kind] || []

  // 限制返回结果数量
  const limitNum = parseInt(limit)
  const limitedData = kindData.slice(0, limitNum)

  // 构建响应数据
  const response = {
    code: 200,
    message: 'success',
    data: limitedData,
    total: kindData.length,
    page: 1,
    limit: limitNum,
  }

  res.json(response)
})

// 获取发现页详情接口 - 根据ID返回不同模块的详细信息
app.get('/api/discover/:id', (req, res) => {
  const id = parseInt(req.params.id)

  // 在各个分类中查找匹配的ID
  let item = null
  let type = ''

  // 在作者列表中查找
  item = discoverData.authors.find((author) => author.id === id)
  if (item) {
    type = 'author'
    // 查找该作者的诗词
    const allPoems = Object.values(poemsData).flat()
    const authorPoems = allPoems.filter((poem) => poem.author === item.name)

    return res.json({
      code: 200,
      message: 'success',
      data: {
        id: item.id,
        type: 'author',
        name: item.name,
        subtitle: item.dynasty,
        description: item.description,
        extraInfo: `共收录${item.count}首诗词`,
        poems: authorPoems.map((poem) => ({
          id: poem.id.toString(),
          title: poem.title,
          author: poem.author,
          dynasty: poem.dynasty,
          content: poem.content.replace(/，/g, '，\n'),
        })),
      },
    })
  }

  // 在主题列表中查找
  item = discoverData.themes.find((theme) => theme.id === id)
  if (item) {
    type = 'theme'
    // 查找该主题的诗词
    const allPoems = Object.values(poemsData).flat()
    const themePoems = allPoems.filter(
      (poem) => poem.tags && poem.tags.includes(item.name)
    )

    return res.json({
      code: 200,
      message: 'success',
      data: {
        id: item.id,
        type: 'theme',
        name: item.name,
        subtitle: `诗词主题 · 共${item.count}首`,
        description: `${item.name}是中国古典诗词中常见的主题之一，表达了诗人对${item.name}的独特感悟。`,
        extraInfo: `共收录${item.count}首相关诗词`,
        poems: themePoems.map((poem) => ({
          id: poem.id.toString(),
          title: poem.title,
          author: poem.author,
          dynasty: poem.dynasty,
          content: poem.content.replace(/，/g, '，\n'),
        })),
      },
    })
  }

  // 在朝代列表中查找
  item = discoverData.dynasties.find((dynasty) => dynasty.id === id)
  if (item) {
    type = 'dynasty'
    // 查找该朝代的诗词
    const allPoems = Object.values(poemsData).flat()
    const dynastyPoems = allPoems.filter((poem) => {
      // 处理朝代名称可能的差异（如"唐代"和"唐"）
      const dynastyName = item.name.replace('代', '')
      return poem.dynasty === dynastyName || poem.dynasty === item.name
    })

    return res.json({
      code: 200,
      message: 'success',
      data: {
        id: item.id,
        type: 'dynasty',
        name: item.name,
        subtitle: item.period,
        description: `${item.name}是中国诗歌发展的重要时期，诗歌数量多、质量高、题材广泛、艺术成就突出。${item.name}诗在中国文学史上占有重要地位。`,
        extraInfo: `共收录${item.count}首诗词`,
        poems: dynastyPoems.map((poem) => ({
          id: poem.id.toString(),
          title: poem.title,
          author: poem.author,
          dynasty: poem.dynasty,
          content: poem.content.replace(/，/g, '，\n'),
        })),
      },
    })
  }

  // 在形式列表中查找
  item = discoverData.forms.find((form) => form.id === id)
  if (item) {
    type = 'form'
    // 由于没有形式标签，这里模拟一些诗词
    const allPoems = Object.values(poemsData).flat()
    // 简单模拟：五言诗和七言诗的判断
    const formPoems = allPoems.filter((poem) => {
      if (
        item.name.includes('五言') &&
        poem.content.split('，')[0].length === 5
      ) {
        return true
      }
      if (
        item.name.includes('七言') &&
        poem.content.split('，')[0].length === 7
      ) {
        return true
      }
      return false
    })

    return res.json({
      code: 200,
      message: 'success',
      data: {
        id: item.id,
        type: 'form',
        name: item.name,
        subtitle: `诗词形式 · 共${item.count}首`,
        description: item.description,
        extraInfo: `【格律】格律要求：首句可平可仄，颔句押韵，颈句转韵，尾句押韵。`,
        poems: formPoems.map((poem) => ({
          id: poem.id.toString(),
          title: poem.title,
          author: poem.author,
          dynasty: poem.dynasty,
          content: poem.content.replace(/，/g, '，\n'),
        })),
      },
    })
  }

  // 如果没有找到匹配的ID
  return res.status(404).json({
    code: 404,
    message: 'Item not found',
  })
})

// 启动服务器
const server = app.listen(PORT, () => {
  console.log(`诗歌服务器运行在 http://localhost:${PORT}`)
})

// 现在可以使用server变量引用HTTP服务器实例
// 例如，可以添加优雅关闭服务器的代码
process.on('SIGTERM', () => {
  console.log('正在关闭服务器...')
  server.close(() => {
    console.log('服务器已关闭')
  })
})
